package com.qf.juc.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo2 {

    public static void main(String[] args) {
        Demo demo = new Demo();
        new Thread(()->{
           demo.A();
        });

        new Thread(()->{
            demo.B();
        });

        new Thread(()->{
            demo.C();
        });

        ThreadLocal<Object> local = new ThreadLocal<>();
    }


}


class Demo{

        private Lock lock = new ReentrantLock();
        private Condition condition1 = lock.newCondition();
        private Condition condition2 = lock.newCondition();
        private Condition condition3 = lock.newCondition();
        int num = 1;

        public void A(){
            lock.lock();
            try{
                while (num!=1){
                    condition1.await();
                }
                System.err.println(Thread.currentThread().getName()+"A");
                num=2;
                condition2.signal();
            }catch (Exception e){
                e.printStackTrace();
                lock.unlock();
            }
        }

    public void B() {
        lock.lock();
        try {
            while (num != 2) {
                condition3.await();
            }
            System.err.println(Thread.currentThread().getName() + "B");
            num = 3;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
            lock.unlock();
        }
    }
        public void C(){
            lock.lock();
            try{
                while (num!=3){
                    condition1.await();
                }
                System.err.println(Thread.currentThread().getName()+"C");
                num=1;
                condition1.signal();
            }catch (Exception e){
                e.printStackTrace();
                lock.unlock();
            }
        }
    }




